package com.core.framework.web.easyweb.dispatcher;

import java.util.Hashtable;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.core.framework.web.easyweb.ActionFactory;
import com.core.framework.web.easyweb.EasyAction;
import com.core.framework.web.easyweb.EasywebStatics;
import com.core.framework.web.easyweb.annotation.MethodType;
import com.core.framework.web.easyweb.forward.ActionForward;
import com.util.AppUtils;
/**
 * 该类负责业务的重定向工作
 * @author: LiuTao
 * @since:Aug 13, 2012
 */
public class DispatcherAction implements EasywebStatics 
{
    private    HttpServletRequest  request ;
    private    HttpServletResponse response;
    private Hashtable<String, Class<?>> webActionClassMap ;
    static ActionForward  actionForward;
    static {
    		
    	if(DispatcherAction.actionForward==null)
    	{
    		actionForward = new ActionForward();
    	}
    }

	public DispatcherAction (HttpServletRequest  _request ,HttpServletResponse _response)
	{
//		request = ServletActionContext.getRequest();
		//	response = ServletActionContext.getResponse();
		request = _request;
		response = _response;
		webActionClassMap = ActionFactory.getInstance().getWebActionClassMap();
	}
	public void excute () 
	{
		try{
		 String extendedName = actionForward.getExpandedName(request);
		 //如果扩展名是HTM  则表示用户直接请求的页面
		 if(extendedName.equals(expandFileName))
		 {
			 String path= actionForward.getPathWithOutExt(request);
			 String truePath = path+extendedName;
			 actionForward.putUrlPageContent(request);//组织URL传过来的参数
			 ActionForward.forward(truePath, request, response);
			 return ;
		 }
		 else if(extendedName.equals(expandDoName)) //如果扩展名是 .ACTION 则加判断处理
		 {
			 String actionMethod = actionForward.getActionMethod(request);
			 String actionPath = actionForward.getActionPath(request);
			 //1.首先判断请求的连接是否在已经加载的WebAction容器里面
			 if(webActionClassMap.containsKey(actionPath))
			 {
				 //2.获取容器里面的Action事件类
				 Class<?> actionObject = webActionClassMap.get(actionPath);
				 EasyAction easy = (EasyAction)AppUtils.autowiredBean(actionObject);
				 easy.init(request,response,actionMethod);
				 String[] forwradData  =  easy.Process();
				 if(forwradData[0]!=null)
				 {
					 if(forwradData[1]==null ||forwradData[1].equals(MethodType.FORWARD) )
					 {
						 ActionForward.forward(forwradData[0], request, response);
					 }
					 else if(forwradData[1].equals(MethodType.REDIRECT))
					 {
						 ActionForward.sendRedirect(forwradData[0], response);
					 }
				 }
			 }
		 
		 }
		}catch(Exception e)
		{
			e.printStackTrace();
		}
	}
}
